package jdk8.Lambda.Stream;

import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Stream;

public class Demo01ForEach {
    @Test
    void test(){
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        List<String> zhangList = new ArrayList<>();
        for (String name : list) {
            if (name.startsWith("张")) {
                zhangList.add(name);
            }
        }
        List<String> shortList = new ArrayList<>();
        for (String name : zhangList) {
            if (name.length() == 3) {
                shortList.add(name);
            }
        }
        for (String name : shortList) {
            System.out.println(name);
        }
    }
    @Test
   void test2(){
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        list.stream().filter(s -> s.startsWith("张"))
                .filter(s -> s.length() == 3)
                .forEach(System.out::println);

    }

    /**
     * 根据Collection获取流
     * 首先， java.util.Collection 接口中加入了default方法 stream 用来获取流，所以其所有实现类均可获取流。
     */
    @Test
    void demo04GetStream(){
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
        Set<String> set = new HashSet<>();
        Stream<String> stream2 = set.stream();

        Map<String, String> map = new HashMap<>();
        Stream<String> keyStream = map.keySet().stream();
        Stream<String> valueStream = map.values().stream();
        Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
//如果使用的不是集合或映射而是数组，由于数组对象不可能添加默认方法，所以 Stream 接口中提供了静态方法
//of ，使用很简单：

        String[] array = {"无张无忌", "张翠山", "张三丰", "张一元"};
        Stream<String> stream = Stream.of(array);
/*虽然方法名字叫forEach，但是与for循环不同
基本使用*/
        stream.forEach(name -> System.out.println(name));
       stream.filter(s -> s.startsWith("张"));
        stream.forEach(s -> System.out.println(s));

    }
}
